<?php

namespace app\common\libs;

use OSS\Core\OssException;
use OSS\OssClient;
use think\Exception;
use yiqiniu\extend\traits\Singleton;

class OssLib
{


    use Singleton;

    protected $ossClient = null;
    protected $bucket = '';
    protected $config = [
        'accessId' => '',
        'accessSecret' => '',
        'endpoint' => '',
        'bucket' => ''
    ];


    public function _initConfig($option)
    {
        $option = current($option);
        $keys = array_keys($this->config);
        $this->config = array_merge($this->config, $option);
        $error = false;
        foreach ($keys as $v) {
            if (empty($this->config[$v])) {
                $error = true;
                break;
            }
        }
        if (!$error) {
            $this->ossClient = new OssClient($this->config['accessId'], $this->config['accessSecret'], $this->config['endpoint']);
            $this->bucket = $this->config['bucket'];
        }
    }

    /**
     * 从OSS中删除文件
     * @param string $filename
     * @return mixed
     * @throws Exception
     */
    public function deleteFile(string $filename)
    {

        if ($this->ossClient === null || $this->bucket === '') {
            throw  new Exception('初始化OSS错误', API_ERROR);
        }
        try {
            if (stripos($filename, 'http') === 0) {
                $path = parse_url($filename)['path'] ?? '';
                if ($path !== '') {
                    $filename = substr($path, 1);
                }
            }
            if (empty($filename)) {
                return true;
            }
            return $this->ossClient->deleteObject($this->bucket, $filename);
        } catch (OssException $e) {
            return false;
        }
    }
}